import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/TencenNewFriendsDao.dart';
import 'package:changxindianzishangwu/dao/common_language_dao.dart';
import 'package:changxindianzishangwu/dao/friends_circle_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/model/common_language_model.dart';
import 'package:changxindianzishangwu/model/friends_lately_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_operation_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import '../home_page.dart';

class UserAddInfoPage extends StatefulWidget {
  V2TimFriendApplication friendApplicationEntity;
  V2TimUserFullInfo userEntity;
  int type;
  UserAddInfoPage(
      {Key key, this.friendApplicationEntity, this.userEntity, this.type})
      : super(key: key);

  @override
  _UserAddInfoPageState createState() => _UserAddInfoPageState();
}

class _UserAddInfoPageState extends State<UserAddInfoPage> {
  _acceptFriend() async {
    print("${_userEntity.userID}userid!!!");
    TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .acceptFriendApplication(
            responseType: 1, type: 1, userID: _userEntity.userID)
        .then((value) async {
      TencentImSDKPlugin.v2TIMManager.getLoginUser().then((value) async {
        await TencenNewFirendsDao.addInfo(
            widget.friendApplicationEntity.addWording,
            widget.friendApplicationEntity.addTime.toString(),
            DateTime.now().millisecondsSinceEpoch.toString(),
            "1",
            widget.userEntity.userID,
            value.data);
      });

      Get.offAll(HomePage(
        pageIndex: 0,
      ));
    });
  }

  V2TimUserFullInfo _userEntity;
  Future<V2TimValueCallback<List<V2TimFriendInfoResult>>> userEntity;
  List<String> userId;
  List<V2TimFriendInfoResult> friendInfoResult;
  _getUserInfoData() async {
    userId = [];

    userId.add(widget.friendApplicationEntity.userID);

    userId.forEach((element) {
      print("=========2" + element);
    });
    userEntity = TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .getFriendsInfo(userIDList: userId);

    if (userEntity != null) {
      userEntity.then((value) {
        friendInfoResult = value.data;
        friendInfoResult.forEach((element) {
          _userEntity = element.friendInfo.userProfile;
          print("这里是数据：：：：${_userEntity.toJson()}");
        });
        setState(() {});
      });
    }
  }

  UserInfoModel userInfoModel;
  var ziYuId = "";
  getServiceData() async {
    print("object1111111");
    userInfoModel = await UserInfoDao.getUserInfo(
        userId: int.parse(widget.friendApplicationEntity.userID));
    setState(() {
      ziYuId = userInfoModel.data.account;
    });
  }

  int a = 0;
  sendMessage(value, length) async {
    print("长度！！！！！！！！" + value);
    print("长度！！！！！！！！" + length.toString());
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
        .v2TIMManager.v2TIMMessageManager
        .sendTextMessage(
      text: value,
      receiver: _userEntity.userID,
    );
    // _messages.insert(_messages.length, res.data);
    List<V2TimMessage> list = new List.empty(growable: true);
    V2TimMessage msg = res.data;
    if (res.code == 0) {
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage("c2c_" + _userEntity.userID, list);
      print("长度！！！！！！！！" + _lists.length.toString());
      if (_lists.length == 1) {
        if (_lists.length == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
          Get.offAll(HomePage(
            pageIndex: 1,
          ));
        }
      } else {
        if (_lists.length - 1 == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
          Get.offAll(HomePage());
        } else if (length == 0) {
          Get.offAll(HomePage(
            pageIndex: 1,
          ));
        }
      }
    } else {
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage("c2c_" + _userEntity.userID, list);
      if (_lists.length == 1) {
        if (_lists.length == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
          Get.offAll(HomePage(
            pageIndex: 1,
          ));
        }
      } else {
        if (_lists.length - 1 == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
          Get.offAll(HomePage(
            pageIndex: 1,
          ));
        } else if (length == 0) {
          Get.offAll(HomePage(
            pageIndex: 1,
          ));
        }
      }
    }
  }

  List<CommonLanguageBean> _lists = [];
  getDataList() async {
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    Map hashMap = await CommonLanguageDao.getData(1);
    if (!hashMap.containsKey("data")) {
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (mounted)
      setState(() {
        _lists.addAll(commonLanguageModel.data);
      });
  }

  @override
  void initState() {
    super.initState();
    getServiceData();
    getDataList();
    _getUserInfoData();
  }

  ap() {
    if (_lists.length > 0) {
      if (_lists.length == 1) {
        sendMessage(_lists[0].context, 1);
      } else {
        for (int i = 0; i <= _lists.length; i++) {
          print("=====================" + i.toString() + "==================");
          sendMessage(_lists[i].context, i);
        }
      }
    } else {
      sendMessage("我们已经是好友了，快来开始聊天吧！～", 0);
    }
  }

  _deleteUserAdd(String type) async {
    if (type == "拒绝") {
      //todo 发送到后台数据

      V2TimValueCallback<V2TimFriendOperationResult> res =
          await TencentImSDKPlugin.v2TIMManager
              .getFriendshipManager()
              .refuseFriendApplication(type: 1, userID: _userEntity.userID);
      if (res.code == 0) {
        showToast("拒绝成功");
        TencentImSDKPlugin.v2TIMManager.getLoginUser().then((value) async {
          await TencenNewFirendsDao.addInfo(
              widget.friendApplicationEntity.addWording,
              widget.friendApplicationEntity.addTime.toString(),
              DateTime.now().millisecondsSinceEpoch.toString(),
              "2",
              widget.userEntity.userID,
              value.data);
        });
      } else {
        print(res.desc);
      }
    } else {
      //todo 删除后台数据

      V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
          .getFriendshipManager()
          .deleteFriendApplication(userID: _userEntity.userID, type: 1);
      print(res.toJson());
      TencentImSDKPlugin.v2TIMManager.getLoginUser().then((value) async {
        await TencenNewFirendsDao.addInfo(
            widget.friendApplicationEntity.addWording,
            widget.friendApplicationEntity.addTime.toString(),
            DateTime.now().millisecondsSinceEpoch.toString(),
            "2",
            widget.userEntity.userID,
            value.data);
      });
    }
    setState(() {});
    Get.offAll(() => HomePage(
          pageIndex: 1,
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  InkWell(
                    onTap: () {},
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: ScreenUtil().setWidth(55),
                          height: ScreenUtil().setWidth(55),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: CachedNetworkImageProvider(
                                  _userEntity.faceUrl == null
                                      ? HEADER_URL
                                      : _userEntity.faceUrl,
                                ),
                                fit: BoxFit.cover),
                            borderRadius:
                                BorderRadius.circular(ScreenUtil().radius(6)),
                          ),
                          child: Text(""),
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(15),
                            left: ScreenUtil().setWidth(15),
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(
                                top: ScreenUtil().setHeight(15),
                                left: ScreenUtil().setWidth(10),
                              ),
                              alignment: Alignment.centerLeft,
                              child: Row(
                                children: [
                                  Text(
                                    _userEntity.nickName ?? "",
                                    style: TextStyle(
                                      fontSize: ScreenUtil().setSp(20),
                                      color: Color.fromRGBO(51, 51, 51, 1),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(left: 6),
                                    child: Image.asset(
                                      _userEntity.gender == 2
                                          ? AppString.IMAGE_NV
                                          : AppString.IMAGE_NAN,
                                      height: height(12),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(10),
                                  top: ScreenUtil().setHeight(1)),
                              alignment: Alignment.centerLeft,
                              child: Text(
                                "用户ID：" + ziYuId,
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12),
                                  color: Color.fromRGBO(153, 153, 153, 1),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setHeight(6)),
                    child: Divider(
                      height: 1,
                      indent: width(80),
                      color: Color.fromRGBO(248, 248, 248, 1),
                      thickness: ScreenUtil().setHeight(1),
                    ),
                  ),
                  // 签名
                  Container(
                    margin: EdgeInsets.only(left: width(80), right: width(15)),
                    padding: EdgeInsets.only(top: width(10), bottom: width(10)),
                    child: Text(
                      "${_userEntity.selfSignature == "" || _userEntity.selfSignature == null ? "" : _userEntity.selfSignature}",
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(12),
                        color: Color.fromRGBO(51, 51, 51, 1),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(top: 18),
                color: Colors.white,
                height: 160,
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 15.w),
                      child: Text(
                        "好友申请",
                        style: TextStyle(
                          fontSize: sp(12),
                          color: ZdColor.rgba(153, 153, 153, 1),
                        ),
                      ),
                      alignment: Alignment.centerLeft,
                    ),
                    Container(
                      width: 345.w,
                      height: 100,
                      padding: EdgeInsets.all(15),
                      alignment: Alignment.topLeft,
                      margin: EdgeInsets.only(top: 10),
                      color: ZdColor.rgba(245, 245, 245, 1),
                      child: Text(
                        widget.friendApplicationEntity.addWording == null ||
                                widget.friendApplicationEntity.addWording
                                        .trim() ==
                                    ""
                            ? "申请添加你为好友～！"
                            : widget.friendApplicationEntity.addWording,
                        style: TextStyle(fontSize: 13.sp, color: Colors.black),
                      ),
                    )
                  ],
                )),
            Container(
              margin: EdgeInsets.only(top: 10),
              color: Colors.white,
              height: 66,
              child: ListTile(
                leading: Text(
                  "动态",
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(15),
                  ),
                ),
                title: Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                    child: getLateLyBuilder()),
                trailing: Icon(Icons.keyboard_arrow_right),
              ),
            ),
            Divider(
              height: 1,
              indent: ScreenUtil().setWidth(15),
              color: Color.fromRGBO(248, 248, 248, 1),
              thickness: ScreenUtil().setHeight(1),
            ),
            Container(
              color: Colors.white,
              height: ScreenUtil().setHeight(55),
              child: ListTile(
                leading: Text(
                  "来源",
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(15),
                  ),
                ),
                trailing: Text(
                  widget.friendApplicationEntity.addSource == "id"
                      ? "用户ID搜索"
                      : "扫一扫搜索",
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(15),
                      color: Color.fromRGBO(153, 153, 153, 1)),
                ),
              ),
            ),
            InkWell(
              onTap: _acceptFriend,
              child: Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                color: Colors.white,
                height: ScreenUtil().setHeight(55),
                child: ListTile(
                  title: Container(
                    alignment: Alignment.center,
                    child: Text(
                      "接受好友申请",
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(15),
                          color: Color.fromRGBO(0, 220, 169, 1)),
                    ),
                  ),
                ),
              ),
            ),
            InkWell(
              onTap: () {
                // //todo 添加好友的时候需要两方的id
                // Get.to(() => UserFirePage(
                //     userId: widget.userId,
                //     nickName: _userEntity.nickName ?? ""));
                _deleteUserAdd("忽略");
              },
              child: Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                color: Colors.white,
                height: ScreenUtil().setHeight(55),
                child: ListTile(
                  title: Container(
                    alignment: Alignment.center,
                    child: Text(
                      "忽略",
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(15),
                          color: ZdColor.rgba(153, 153, 153, 1)),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  getLateLyBuilder() {
    return FutureBuilder(
        future: getLateLy(),
        builder: (context, sp) {
          if (sp.connectionState == ConnectionState.done && sp.data != null) {
            List<LatelyBean> data = sp.data;
            return ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: data.length,
                itemBuilder: (context, int index) {
                  return Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(8)),
                    child: HeadView(
                      data[index].type == 2 && data[index].url != null
                          ? data[index].url
                          : BACKGROUND_IMAGE,
                      width(50),
                      width(50),
                    ),
                  );
                });
          } else {
            return SizedBox();
          }
        });
  }

  getLateLy() async {
    return await FriendsCircleDao.getFriendsLately(_userEntity.userID);
  }
}
